package com.ccc.services;

import com.ccc.Mapper.demo;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.jupiter.api.BeforeEach;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import com.ccc.Beans.user;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@Component
@Service
public class services {

    private static demo Demo;
    private static SqlSession sqlSession;
    static {
        String res = "mybatis-config.xml";
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream(res);
        } catch (IOException e) {
            e.printStackTrace();
        }
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        sqlSession = sqlSessionFactory.openSession();
        Demo = sqlSession.getMapper(demo.class);
    }

    public int saveUser(user user1) {
        List<user> list = Demo.selectAll();
        int i = 0;
        if (list != null) {
            for (user list1 : list) {
                if (list1.getUsername().equals(user1.getUsername())) //检查数据库用户是否已存在
                {
                    i = 1;
                    break;
                }
            }
            if (i == 0) {
                if (!(user1.getUsername().length() >= 8 && user1.getPassword().length() <= 16))
                    return 0;
                else {
                    Demo.Insert1(user1.getPassword(), user1.getUsername());
                    sqlSession.commit();
                    sqlSession.close();
                    return 1;//插入成功
                }
            } else {
                return 0;//插入失败
            }
        } else {
            if (!(user1.getUsername().length() >= 8 && user1.getPassword().length() <= 16))
                return 0;
            else {
                Demo.Insert1(user1.getPassword(), user1.getUsername());
                sqlSession.commit();
                sqlSession.close();
                return 1;//插入成功
            }
        }
    }
}
